//
//  WBRefreshControl.swift
//  weibo
//
//  Created by 吴婷婷 on 15/11/13.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit
import SnapKit

private let WBRefreshControlOffset: CGFloat = -60

class WBRefreshControl: UIRefreshControl {
    //MARK: - 构造函数
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        
//        setupUI()
//    }
    
    ///MARK: - 重写系统方法
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.endAnimation()
    }
    
    override func beginRefreshing() {
        super.beginRefreshing()
        
        refreshView.startAnimation()
    }
    
    ///监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(frame)
        
        if frame.origin.y > 0 { return }
        
        if refreshing {
            refreshView.startAnimation()
            return
        }
        
        if frame.origin.y < WBRefreshControlOffset && !refreshView.rotateFlag {
            refreshView.rotateFlag = true
        } else if frame.origin.y > WBRefreshControlOffset && refreshView.rotateFlag {
            refreshView.rotateFlag = false
        }
    }
    
    //MARK: - 构造函数
    override init() {
        super.init()
        
        setupUI()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
    }

    ///懒加载
    private lazy var refreshView = WBRefreshView.refreshView()
    
    
    //设置界面
    private func setupUI() {
        tintColor = UIColor.clearColor()
        
        addSubview(refreshView)
        
        refreshView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.centerY.equalTo(self.snp_centerY)
            make.size.equalTo(refreshView.bounds.size)
        }
        //添加监听事件
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        
        }
    }
    //销毁监听事件
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }


}
//MARK: - 从xib加载刷新视图
class WBRefreshView: UIView {
    @IBOutlet weak var tipIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var loadingIcon: UIImageView!
    
    ///旋转标识
    var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    
    ///旋转箭头动画
    func rotateTipIcon() {
        
        let angle = rotateFlag ? CGFloat(M_PI) - 0.00001 : CGFloat(M_PI) + 0.00001
        
        UIView.animateWithDuration(0.2) { () -> Void in
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, angle)
        }
    }
    ///开始旋转加载图标
    private func startAnimation() {
        tipView.hidden = true
        
        let key = "transform.rotation"
        if loadingIcon.layer.animationForKey(key) != nil {
            return
        }

        let anim = CABasicAnimation(keyPath: key)
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1
        anim.removedOnCompletion = false
        
        loadingIcon.layer.addAnimation(anim, forKey: key)

    }
    
    ///停止旋转加载中图标
    private func endAnimation() {
        tipView.hidden = false
        
        loadingIcon.layer.removeAllAnimations()
    }
    
    ///加载Xib
    class func refreshView() -> WBRefreshView {
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nib, options: nil)[0] as! WBRefreshView
    }
}


